package com.wf.atm.client;


import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;


/**
 * @Author fqq
 * @Date 2022/11/8 14:38
 * <p>
 * ATMClient  客户端
 */
public class ATMClient extends JFrame {

    //JPanel
    MainPanel mainPanel;
    LoginPanel loginPanel;
    RegisterPanel registerPanel;
    BusinessPanel businessPanel;

    // Bank bank=Bank.getInstance();

    //通信资源
    Socket socket;//当前的客户端套接字
    PrintWriter printWriter;//发送指令
    ObjectInputStream ois;//读取执行结果


    public ATMClient() {


        try {

            this.socket = new Socket("localhost", 8090);

            this.printWriter = new PrintWriter(socket.getOutputStream());

            this.ois = new ObjectInputStream(socket.getInputStream());

        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }


        //监听客户端的窗口关闭事件：发送指令给服务器，告知他 我已下线
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                //1.发送登录指令  close
                printWriter.println("close");
                printWriter.flush();
                System.out.println("close");
                try {
                    //2.等待读取服务器的执行结果 空读 程序不阻塞
                   // Object result = ois.readObject();
                    //关闭客户端的socket
                    socket.close();
                } catch (SocketException ex) {
                    JOptionPane.showMessageDialog(null, "服务器已关闭，请稍后再试");
                    System.exit(0);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
        //设置窗体基本的信息
        this.setTitle("ATM取款机");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(500, 650);
        //居中显示
        this.setLocationRelativeTo(getOwner());


        //实例化JPanel界面
        mainPanel = new MainPanel(this);
        loginPanel = new LoginPanel(this);
        registerPanel = new RegisterPanel(this);
        businessPanel = new BusinessPanel(this);

        //将JPanel添加至JFrame的容器中
        Container container = this.getContentPane();
        //将容器设置为卡片式布局
        container.setLayout(new CardLayout());
        //默认MainPanel显示在第一个
        container.add(mainPanel, "mainPanel");
        container.add(loginPanel, "loginPanel");
        container.add(registerPanel, "registerPanel");
        container.add(businessPanel, "businessPanel");

    }

    public static void main(String[] args) {
        new ATMClient().setVisible(true);
    }
}
